package cn.tjad.tjad2.module.construction.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.activity.BaseActivity;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.utils.UrlUtils;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.IDataCallBack;
import com.qiandian.android.base.widget.TJADTTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.consts.TjadConsts;
import cn.tjad.tjad2.consts.UrlConsts;
import cn.tjad.tjad2.data.bean.Attach;
import cn.tjad.tjad2.data.bean.ConstructionDetail;
import cn.tjad.tjad2.data.bean.FileBean;
import cn.tjad.tjad2.data.event.ConstructionStatusChangedEvent;
import cn.tjad.tjad2.module.construction.widget.ConstructionStatus;
import cn.tjad.tjad2.net.TjadHttpServer;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.DocumentHelper;
import cn.tjad.tjad2.utils.NetworkUtils;
import cn.tjad.tjad2.utils.QRCodeUtils;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.widget.PictureLoadView;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;

@Route(path = PageId.CONSTRUCTION_DETAIL)
public class ConstructionDetailActivity extends BaseActivity implements IDataCallBack {

    @BindView(R.id.construction_detail_code)
    TextView codeTV;
    @BindView(R.id.construction_detail_floor)
    TextView floorTV;
    @BindView(R.id.construction_detail_type)
    TextView typeTV;
    @BindView(R.id.construction_detail_status)
    TextView statusTV;
    @BindView(R.id.construction_detail_related_model)
    TextView relatedModelTV;
    @BindView(R.id.construction_detail_attachment_container)
    LinearLayout attachmentContainer;
    @BindView(R.id.construction_detail_description)
    TextView descriptionTV;
    @BindView(R.id.construction_detail_qrcode_image)
    ImageView qrcodeIV;
    @BindView(R.id.construction_detail_progress_container)
    FrameLayout progressContainer;
    @BindView(R.id.construct_detail_picture_load_view)
    PictureLoadView pictureLoadView;

    private int projectId;
    private int constructionId;
    private ConstructionStatus constructionStatus;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.construction_detail);
        EventBus.getDefault().register(this);
        constructionStatus = new ConstructionStatus(this);
        handleExtras(getIntent());
    }

    private void handleExtras(Intent intent) {
        constructionId = intent.getIntExtra(Keys.CONSTRUCTION_ID, -1);
        if (constructionId == -1) {
            Tools.showToast("没有传入有效的参数");
            finish();
            return;
        }
        requestConstructionDetail();

    }

    private void requestConstructionDetail() {
        projectId = TjadApplication.getInstance().getSession().getProjectId();
        RemoteDataService.constructionDetail(projectId, constructionId, this);
    }

    @Override
    public void onTitleClick(int which) {
        super.onTitleClick(which);
        switch (which) {
            case TJADTTitleView.TITLE_RIGHT:
                //打开视口
//                openViewEntry();
                ConstructionDetail constructionDetail = (ConstructionDetail) getTitleView().getTag();
                if (constructionDetail == null) {
                    return;
                }
                DocumentHelper.openModelFile(this, constructionDetail.document, "ctId", constructionId);
                break;
        }
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        if (httpId == HttpId.CONSTRUCTION_DETAIL) {
            if (TextUtils.isEmpty(errorMsg)) {
                Tools.showToast("获取施工详情失败");
            } else {
                Tools.showToast(errorMsg);
            }
        }
        return false;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        if (httpId == HttpId.CONSTRUCTION_DETAIL) {
            CommonBean<ConstructionDetail> bean = (CommonBean<ConstructionDetail>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                fillConstructionDetail(bean.result);
            } else {
                Tools.showToast(bean.respMsg);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void fillConstructionDetail(ConstructionDetail result) {
        if (result.document != null) {
            getTitleView().setRightImage(R.drawable.icon_view_entrance);
            getTitleView().showRight(true);
            getTitleView().setTag(result);
        } else {
            getTitleView().showRight(false);
            getTitleView().setTag(null);
        }
        codeTV.setText(result.code);
        if (result.floor != null) {
            floorTV.setText(result.floor.name);
        } else {
            floorTV.setText("");
        }
        if (result.type != null) {
            typeTV.setText(result.type.name);
        } else {
            typeTV.setText("");
        }
        String status = Tools.getConsStatusByCode(result.consStatus);
        statusTV.setText(status.trim());
        if (result.document != null) {
            relatedModelTV.setText(result.document.name);
        }
        descriptionTV.setText(result.content);
        attachmentContainer.removeAllViews();
        attachmentContainer.setGravity(Gravity.CENTER_VERTICAL);
        if (result.attaches != null && result.attaches.size() > 0) {
            for (Attach attach : result.attaches) {
                if (attach != null && attach.relateFile != null) {
                    TextView textView = new TextView(this);
                    String name = attach.relateFile.name;
                    textView.setText(name);
                    textView.setMaxLines(1);
                    textView.setEllipsize(TextUtils.TruncateAt.END);
                    int iconImage = Tools.getFileSmallIcon(name.substring(name.lastIndexOf(".") + 1));
                    textView.setCompoundDrawablesWithIntrinsicBounds(iconImage, 0, 0, 0);
                    textView.setCompoundDrawablePadding(getResources().getDimensionPixelSize(R.dimen.dp_5));
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    textView.setTag(attach.relateFile);
                    textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                    textView.setTextColor(Color.BLUE);
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            FileBean fileBean = (FileBean) view.getTag();
                            if (fileBean != null) {
                                viewOnlineFileWithNetStatus(fileBean);
                            }
                        }
                    });
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    attachmentContainer.addView(textView, lp);
                }
            }
        }
        Bitmap qrBitmap = QRCodeUtils.createQRCodeBitmap(result.qrUrl, qrcodeIV.getWidth(), qrcodeIV.getHeight());
        if (qrBitmap != null) {
            qrcodeIV.setImageBitmap(qrBitmap);
        }
        pictureLoadView.setImageUrls(result.finishPhotos);
        constructionStatus.setConstructionDetail(result);
        View constrctionStatusView = constructionStatus.getView();
        progressContainer.removeAllViews();
        if (constrctionStatusView != null) {
            progressContainer.addView(constrctionStatusView);
        }

    }

    private void viewOnlineFileWithNetStatus(final FileBean fileBean) {
        if (!NetworkUtils.isNetworkConnected(this)) {
            Tools.showToast("网络连接失败, 请检查网络!");
            return;
        }
        if (!NetworkUtils.isWifi(this)) {
            TjDialogFragment.Builder builder = new TjDialogFragment.Builder(this);
            builder.setTitle("提示")
                    .setMessage("您当前为非WIFI网络, 是否继续?")
                    .setPositiveButton("继续", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialogInterface, int i) {
                            viewOnlineFile(fileBean);
                            return true;
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show(getSupportFragmentManager());
        } else {
            viewOnlineFile(fileBean);
        }
    }

    //预览在线文件
    private void viewOnlineFile(FileBean fileBean) {
        if (fileBean == null) {
            return;
        }
        if (fileBean.document != null && "0".equals(fileBean.document.forgeStatus)) {
            String localPath = TjadConsts.APPHTML;
            int id = fileBean.document.id;
            String token = TjadApplication.getInstance().getSession().getToken();
            String url = UrlUtils.getUrl(UrlConsts.REMOTE_DOCUMENT_PREVIEW_URL, "" + TjadHttpServer.PORT, localPath,
                    String.valueOf(projectId), token, String.valueOf(id));
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            RouteUtils.toPage(this, PageId.WEBVIEW, bundle);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        constructionStatus.onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe
    public void onConstructionStatusChanged(ConstructionStatusChangedEvent event) {
        if (event.isChanged()) {
            requestConstructionDetail();
        }
    }
}
